package com.baidu.fengchao.broad.action;

import com.baidu.fengchao.broad.bo.Link;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojiangang
 * Date: 13-5-2
 * Time: 下午11:11
 */
@IocBean
public class Nav {
    private Dao dao;

    public void setDao(Dao dao) {
        this.dao = dao;
    }

    @At("/main")
    @Ok("ioc:freemarker")
    @Fail("json")
    public Object nav(){
        Map<String,List<List<Link>>> result = new HashMap<String, List<List<Link>>>();
        List<Link> links = dao.query(Link.class, null);
        Link addLink = new Link();
        addLink.setHref("#addlink");
        addLink.setTitle("CREATE NEW");
        links.add(addLink);
        List<List<Link>> rowLinks = new LinkedList<List<Link>>();
        int count = 0;
        List<Link> row = new LinkedList<Link>();
        for (Link link:links){
            row.add(link);
            if(++count%4 == 0){
                rowLinks.add(row);
                row = new LinkedList<Link>();
            }else if(count == links.size()){
                rowLinks.add(row);
            }
        }


        result.put("links",rowLinks);
        return  result;
    }

    @At("/nav/del")
    @Ok("raw")
    @Fail("json")
    public void del(int id){
        dao.delete(Link.class,id);
    }

    @At("/nav/new")
    @Ok("raw")
    @Fail("json")
    public void add(String title,String href){
        Link link = new Link();
        link.setTitle(title);
        link.setHref(href);

        dao.insert(link);
    }


    @At("/nav/mod")
    @Ok("raw")
    @Fail("json")
    public void mod(int id,String title,String href){
        Link link = dao.fetch(Link.class,id);
        link.setTitle(title);
        link.setHref(href);

        dao.update(link);
    }
}
